package com.Travit;

import java.io.Console;



import java.io.UnsupportedEncodingException;
import android.view.View;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.zxing.integration.android.IntentIntegrator;

import java.net.URI;
import java.net.URISyntaxException;

import android.*;
//import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class TravITActivity extends Activity {
	/** Called when the activity is first created. */
	Button loginButton;
	EditText usernameTextField, passwordTextField;
	TextView usernameLabel, passwordLabel;
	ImageButton searchProductImageButton;
	ImageButton scanBarCodeImageButton;
	ImageButton userManageProfileImageButton;
	ImageButton gobackImageButton;
	ImageButton homepageImageButton;
	ImageButton searchStoreIconImageButton;
	ImageButton logoutImageButton;
	Button clearLoginScreen;
	
	Button newuser;
	Button homepage;
	Button savenewuser;
	Button deleteProfileUserButton;
	Button updateProfileUserButton;
	Button goToLoginPage;
	Button goToNewUserPage;
	Button searchStoresByCityButton;
	Button searchParticularProduct;
	ListView searchProductsListView;
	
	Spinner productCategory;
	Spinner productName;
	
	String tempName;
	String tempCategory;
	String loggedinuser;
	public boolean savehistory = false;
	
	private static String listOfStores[] = { "", "Food Maxx", "Trader Joes",
			"Safeways" };
	private static String listOfStoresCity[] = { "", "San Jose", "Milpitas",
			"Cupertino" };
	private static String loggedid;
	private static String loggedin;
	private static String urlRequestSearchProducts = "http://project492.engr.sjsu.edu/travITsearchProduct.php";
	private static String urlRequest = "http://project492.engr.sjsu.edu/travIT.php";
	private static String urlBarCodeRequest = "http://project492.engr.sjsu.edu/travITsearchBarcode.php";
	private static String urlRequestForHistory = "http://project492.engr.sjsu.edu/travITgetScanDetailsUser.php";
	private static String urlRequestSearchStores = "http://project492.engr.sjsu.edu/travITsearchStores.php";
	/*
	 private static String urlRequest="http://127.0.0.1/travIT.php";
	 private static String urlRequestSearchStores = "http://17.0.0.1/travITsearchStores.php";
	private static String urlRequestSearchProducts = "http://127.0.0.1/travITsearchProduct.php";
	
	private static String urlRequestSearchProducts = "http://10.185.5.176/travITsearchProduct.php";
	 private static String urlRequest="http://10.185.5.176/travIT.php";
	private static String urlRequestSearchStores = "http://10.185.5.176/travITsearchStores.php";
	*/
	Button clearnewUserForm;
	private boolean rightCredentials = false;
	private static int count = 0;// This is to see the level of clicks for the
									// products information;

	// final AlertDialog.Builder builder=new AlertDialog.Builder(this);

	// AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		/*
		 * StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		 * .detectDiskReads() .detectDiskWrites() .detectNetwork() // or
		 * .detectAll() for all detectable problems .penaltyLog() .build());
		 * StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		 * .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects()
		 * .penaltyLog() .penaltyDeath() .build());
		 */
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.receiving);
		setContentView(R.layout.landingpage);
		Log.i("back to", "main page");
		goToLoginPage = (Button) findViewById(R.id.goToLoginPage);
		goToNewUserPage = (Button) findViewById(R.id.goToNewUserPage);
		goToLoginPage.setOnClickListener(new clicker());
		goToNewUserPage.setOnClickListener(new clicker());
		/*
		 * loginButton=(Button)findViewById(R.id.loginButton);
		 * usernameTextField=(EditText)findViewById(R.id.usernameTextField);
		 * passwordTextField=(EditText)findViewById(R.id.passwordTextField);
		 * usernameLabel=(TextView)findViewById(R.id.usernameLabel);
		 * passwordLabel=(TextView)findViewById(R.id.passwordLabel);
		 * loginButton.setOnClickListener(new clicker());
		 * newuser=(Button)findViewById(R.id.newUser);
		 * newuser.setOnClickListener(new clicker());
		 * clearLoginScreen=(Button)findViewById(R.id.clearLoginScreenButton);
		 */

	}
	
	public class clicker implements Button.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			System.out.println("Here:" + v.toString());

			if (v == loginButton) {
				
				
				Log.i("start", "from here");
				// alertbox.setMessage("LoggedIn!");
				Log.v("her----------------------e", "ere");
				HttpClient client = new DefaultHttpClient();
				usernameTextField = (EditText) findViewById(R.id.usernameTextField);
				passwordTextField = (EditText) findViewById(R.id.passwordTextField);
				Log.v("--", usernameTextField.getText().toString());
				loggedinuser = "" + usernameTextField.getText().toString();
				Log.v("string version", loggedinuser);
				//this.createMessage(""+usernameTextField.getText().length());
				// System.out.println(usernameTextField.getText());
				if (usernameTextField.getText().length() >= 1
						|| passwordTextField.getText().length() >= 1) {
					HttpGet request = new HttpGet(urlRequest + "?username="
							+ usernameTextField.getText().toString()
							+ "&userpass="
							+ passwordTextField.getText().toString());

					HttpParams params = new BasicHttpParams();
					List<NameValuePair> pairs = new ArrayList<NameValuePair>();
					pairs.add(new BasicNameValuePair("username",
							usernameTextField.getText().toString()));
					pairs.add(new BasicNameValuePair("userpass",
							passwordTextField.getText().toString()));
					// request.setParams(params);
					Log.v("line157","yeah");
					try {
						
						HttpResponse response = client.execute(request);
						HttpEntity entity = response.getEntity();
						String responseResult = EntityUtils.toString(entity);
						Log.v("line162","yeah");
						// Hashtable<String,String> table=responseResult;
						Log.v("LOGIN:",responseResult);
						Log.v("len", "" +responseResult.length());
						String[] table = responseResult.split(",");
						Log.v("tablelen", "" +table.length);
						Hashtable<String, String> tableHashtable = new Hashtable<String,String>();
						for (int i = 0; i < table.length; i++) {
							Log.v("i:"+i,table[i]);
							if(i==0)
								table[i]=table[i].trim();
							tableHashtable.put(table[i], table[++i]);
						}
						if (tableHashtable.get("status").equals("Accept")) {
							loggedid = tableHashtable.get("ID");
							loggedin = tableHashtable.get("usertype");
							rightCredentials = true;

						} else {
							this.createMessage("Wrong Password. Please Enter the password again");
							usernameTextField.setText("");
							passwordTextField.setText("");
							rightCredentials = false;

						}

					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					this.createMessage("Username or Password cannot be blank. Please enter the username and password again");
					rightCredentials = false;

				}

				// HttpPost request=new
				// HttpPost("http://192.168.3.138/travIT.php");
				// usernameTextField=(EditText)findViewById(R.id.usernameTextField);
				// passwordTextField=(EditText)findViewById(R.id.passwordTextField);
				//
				// // HttpParams params=new BasicHttpParams();
				// List<NameValuePair> pairs = new ArrayList<NameValuePair>();
				// pairs.add(new BasicNameValuePair("username",
				// usernameTextField.getText().toString()));
				// pairs.add(new BasicNameValuePair("userpass",
				// passwordTextField.getText().toString()));
				// request.setEntity(new UrlEncodedFormEntity(pairs));
				// //client.getParams().setParameter("username",
				// usernameTextField.getText().toString());
				// //client.getParams().setParameter("userpass",
				// passwordTextField.getText().toString());
				// Log.v("making request",request.toString());
				// //String
				// param="?username="+usernameTextField.getText().toString()+"&userpass="+passwordTextField.getText().toString();
				// //Log.v("final rquest",request.toString());
				// //URI website = new
				// URI("http://192.168.3.138/travIT.php"+param);
				//
				// //request.setURI(website);
				//
				// Log.v("ffinal",request.toString());
				// HttpResponse response=client.execute(request);
				// Log.v("reposnse",response.getProtocolVersion().toString());
				// Log.v("reposnse",response.toString());
				//
				// Log.v("RESPOSE", response.getAllHeaders().toString());
				// Log.v("RESPOSE", response.getEntity().toString());
				// Log.v("RESPOSE", response.getParams().toString());
				// Log.v("RESPOSE", response.getStatusLine().toString());
				// HttpEntity entity=response.getEntity();
				// // String responseResult=EntityUtils.toString(entity);
				// // builder.setMessage(responseResult);
				// //builder.show();
				// // Log.v("GET::",responseResult);
				// //String[] resResult=responseResult.split(",");
				// // Log.v("hi:", ""+resResult[resResult.length-1].toString());
				// Log.v("::::::::", EntityUtils.toString(entity));

				if(rightCredentials && loggedin.equalsIgnoreCase("vendor"))
				{
					Log.v("liine264", ""+v.getContext());
					Intent newIntent = new Intent(v.getContext(), Vendor.class);
					newIntent.putExtra("venid", loggedid);
					newIntent.putExtra("loginname", usernameTextField.getText());
					startActivity(newIntent);
					//Log.i("login", "distributor");
				}
				if(rightCredentials && loggedin.equalsIgnoreCase("distributor"))
				{
					Log.v("liine265", ""+v.getContext());
					Intent newIntent = new Intent(v.getContext(), Distributor.class);
					newIntent.putExtra("loggedid", loggedid);
					Log.v("loggedin id is: ", loggedid);
					newIntent.putExtra("loginname", loggedinuser);
					Log.i("login", "distributor");
					startActivity(newIntent);
				}
				if(rightCredentials && loggedin.equalsIgnoreCase("retail"))
				{
					Log.v("liine266", ""+v.getContext());
					Intent newIntent = new Intent(v.getContext(), Retail.class);
					newIntent.putExtra("loggedid", loggedid);
					newIntent.putExtra("loggedinuser", loggedinuser);
					Log.v("about", "to start");
					Log.i("login", "retail");
					startActivity(newIntent);
				}

				if (rightCredentials && loggedin.equalsIgnoreCase("user")) {
					Editable username = usernameTextField.getText();
					usernameLabel.setText("Homepage" + username + "!");
					String password = passwordTextField.getText().toString();
					byte[] pass = password.getBytes();
					// temp.setText(password);
					// usernameTextField.setText("Welcome"+username);
					// usernameTextField.setVisibility(View.INVISIBLE);
					// passwordLabel.setVisibility(View.INVISIBLE);
					// passwordTextField.setVisibility(View.INVISIBLE);
					// loginButton.setVisibility(View.INVISIBLE);
					Log.i("login", "user");
					setContentView(R.layout.homepage);
					setTitle(R.string.userhome);
					searchProductImageButton = (ImageButton) findViewById(R.id.searchProductIcon);
					scanBarCodeImageButton = (ImageButton) findViewById(R.id.scanBarcodeIcon);
					userManageProfileImageButton = (ImageButton) findViewById(R.id.userManageProfile);
					// homepageImageButton=(ImageButton)findViewById(R.id.homepageButton);
					// gobackImageButton=(ImageButton)findViewById(R.id.goBackButton);
					searchStoreIconImageButton = (ImageButton) findViewById(R.id.searchStoreIcon);
					logoutImageButton = (ImageButton) findViewById(R.id.logout);
					TextView name = (TextView) findViewById(R.id.homepageUsername);
					name.setText("Welcome " + username + "!");
					// searchImageButton.setImageResource(R.drawable.search);
					// scanBarCodeImageButton.setImageResource(R.drawable.scanbarcode);
					// userManageProfileImageButton.setImageResource(R.drawable.userprofilemanagement);
					// homepageImageButton.setImageResource(R.drawable.homepage);
					// gobackImageButton.setImageResource(R.drawable.go_back);
					// searchStoreIconImageButton.setImageResource(R.drawable.search_store);
					// logoutImageButton.setImageResource(R.drawable.logout);
					// alertbox.show();
					logoutImageButton.setOnClickListener(this);
					// homepageImageButton.setOnClickListener(this);
					// gobackImageButton.setOnClickListener(this);
					userManageProfileImageButton.setOnClickListener(this);
					searchStoreIconImageButton.setOnClickListener(this);
					searchProductImageButton.setOnClickListener(this);
					scanBarCodeImageButton.setOnClickListener(this);
				}
			}else if(v==scanBarCodeImageButton){
				Log.v("in scanning barcode","image button");
				/*
				        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				        intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
				        //startActivityForResult(intent, 0);
				        IntentIntegrator.initiateScan(TravITActivity.this);
				        WORKING CODE*/
				//Trying something new
				savehistory = true;
		        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		        intent.setPackage("com.google.zxing.client.android");
		        intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
		        startActivityForResult(intent, 0);
				       
				       /* 
				                    String contents = intent.getStringExtra("SCAN_RESULT");
				                    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
				                    // Handle successful scan
				                    Log.v("PRINTING", "YAY");
				                    Log.v("PRINTING", "YAY");
				                    Log.v("PRINTING", "YAY");
				                    Log.v("content",contents);
				                    Log.v("format",format);
				                    Log.v("PRINTING", "YAY");
				                    Log.v("PRINTING", "YAY");
				                    Log.v("PRINTING", "YAY");
				                    */
				                    
				        /*
				public void onActivityResult(int requestCode, int resultCode, Intent intent) {
				    if (requestCode == 0) {
				        if (resultCode == RESULT_OK) {
				            String contents = intent.getStringExtra("SCAN_RESULT");
				            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
				            // Handle successful scan
				        } else if (resultCode == RESULT_CANCELED) {
				            // Handle cancel
				        }
				    }
				}
				*/
				
			} 	else if (v == searchStoreIconImageButton) {
				Editable username = usernameTextField.getText();
				setContentView(R.layout.search_stores);
				setTitle(R.string.searstore);
				usernameLabel.setText("Homepage" + username + "!");

				searchStoresByCityButton = (Button) findViewById(R.id.searchStoresByCityButton);
				searchStoresByCityButton.setOnClickListener(this);
				homepageImageButton = (ImageButton) findViewById(R.id.homepageButton);
				homepageImageButton.setOnClickListener(this);
				Spinner listOfItems = (Spinner) findViewById(R.id.storeNameListViewSpinner);
				Spinner listOfStoreStates = (Spinner) findViewById(R.id.searchByCityListSpinner);
				logoutImageButton = (ImageButton) findViewById(R.id.logout);
				logoutImageButton.setOnClickListener(this);
				Log.v("XXXXX","populating the search store icon image button with store city list");
				HttpClient client = new DefaultHttpClient();
				Log.v("TAG::", "City List");
				HttpGet request = new HttpGet(urlRequestSearchStores
						+ "?nameOfStoreList="+true);
				try{
					HttpResponse response=client.execute(request);
					HttpEntity entity = response.getEntity();
					Log.v("entity:",entity.toString());
					String responseResult = EntityUtils.toString(entity);
					Log.v("name of all citires of all stores result::",responseResult);
					Log.v("response result",""+responseResult.charAt(2));
					Log.v("hahahahhahaha","hahahahhaha");
					String listOfStoreCities=";"+responseResult;
					String[]nameOfAllCities=listOfStoreCities.split(";");
					
					ArrayAdapter adapter1 = new ArrayAdapter(TravITActivity.this,
							android.R.layout.simple_spinner_item, nameOfAllCities);
					listOfStoreStates.setAdapter(adapter1);
				
				}
				catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				//Now getting the list of all the stores
				request = new HttpGet(urlRequestSearchStores
						+ "?differentStoreList="+true);
				try{
					HttpResponse response=client.execute(request);
					HttpEntity entity = response.getEntity();
					Log.v("entity:",entity.toString());
					String responseResult = EntityUtils.toString(entity);
					Log.v("name of all stores result::",responseResult);
					Log.v("response result",""+responseResult.charAt(2));
					Log.v("hahahahhahaha","hahahahhaha");
					String listOfStoreNames=";"+responseResult;
					String[]nameOfAllStores=listOfStoreNames.split(";");
					ArrayAdapter adapter = new ArrayAdapter(TravITActivity.this,
							android.R.layout.simple_spinner_item, nameOfAllStores);
					listOfItems.setAdapter(adapter);
				
				}
				catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				} else if (v == searchStoresByCityButton) {
				Spinner listOfStoreNames = (Spinner) findViewById(R.id.storeNameListViewSpinner);
				Spinner listOfStoreStates = (Spinner) findViewById(R.id.searchByCityListSpinner);
				logoutImageButton = (ImageButton) findViewById(R.id.logout);
				logoutImageButton.setOnClickListener(this);

				if (listOfStoreNames.getSelectedItemPosition() == 0
						&& listOfStoreStates.getSelectedItemPosition() == 0) {
					this.createMessage("Both the Store Name and the City  cannot be empty");
				} else {
					HttpClient client = new DefaultHttpClient();
					Log.v("TAG::", listOfStoreNames.getSelectedItem()
							.toString());
					HttpGet request = new HttpGet(urlRequestSearchStores
							+ "?storeName="
							+ Uri.encode(listOfStoreNames.getSelectedItem()
									.toString())
							+ "&storeCity="
							+ Uri.encode(listOfStoreStates.getSelectedItem()
									.toString()));
					try {
						HttpResponse response = client.execute(request);
						HttpEntity entity = response.getEntity();
						String responseResult = EntityUtils.toString(entity);
						if (responseResult.equals("")) {
							responseResult = "No Results";
						}
						Log.v("search result response", responseResult);
						String listOfStores[] = responseResult.split(";");
						setContentView(R.layout.search_stores_result);
						setTitle(R.string.searstore);
						ListView searchStoreByCityResultsView = (ListView) findViewById(R.id.searchStoresResultList);
						searchStoreByCityResultsView
								.setAdapter(new ArrayAdapter<String>(
										TravITActivity.this,
										android.R.layout.simple_list_item_1,
										listOfStores));
						homepageImageButton = (ImageButton) findViewById(R.id.homepageButton);
						homepageImageButton.setOnClickListener(this);
						logoutImageButton = (ImageButton) findViewById(R.id.logout);
						logoutImageButton.setOnClickListener(this);

						// searchStoreByCityResultsView.setAdapter(new
						// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
						// tempArr));
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// setContentView(R.layout.search_stores_result);
				}

			} else if (v == logoutImageButton) {

				Log.i("logout", "user");
				setContentView(R.layout.main);
				setTitle(R.string.loginpg);
				loginButton = (Button) findViewById(R.id.loginButton);
				// usernameTextField=(EditText)findViewById(R.id.usernameTextField);
				// passwordTextField=(EditText)findViewById(R.id.passwordTextField);
				// usernameLabel=(TextView)findViewById(R.id.usernameLabel);
				// passwordLabel=(TextView)findViewById(R.id.passwordLabel);

				loginButton.setOnClickListener(this);
				newuser = (Button) findViewById(R.id.newUser);
				newuser.setOnClickListener(this);
				this.createMessage("You have been logged out!.");

			} else if (v == goToLoginPage) {
				Log.i("mark", "this");
				setContentView(R.layout.main);
				setTitle(R.string.loginpg);
				loginButton = (Button) findViewById(R.id.loginButton);
				usernameTextField = (EditText) findViewById(R.id.usernameTextField);
				passwordTextField = (EditText) findViewById(R.id.passwordTextField);
				usernameLabel = (TextView) findViewById(R.id.usernameLabel);
				passwordLabel = (TextView) findViewById(R.id.passwordLabel);
				loginButton.setOnClickListener(new clicker());
				newuser = (Button) findViewById(R.id.newUser);
				newuser.setOnClickListener(new clicker());
				clearLoginScreen = (Button) findViewById(R.id.clearLoginScreenButton);
			} else if (v == goToNewUserPage) {
				setContentView(R.layout.newuser);
				setTitle(R.string.newuser);
				homepage = (Button) findViewById(R.id.backTohomepagefromnewUsr);
				homepage.setOnClickListener(this);
				EditText username = (EditText) findViewById(R.id.newuser_username);
				EditText password = (EditText) findViewById(R.id.newuser_userpass);
				EditText confirmpassword = (EditText) findViewById(R.id.newuser_userpass1);

				savenewuser = (Button) findViewById(R.id.savenewUser);
				savenewuser.setOnClickListener(this);

				//clearnewUserForm = (Button) findViewById(R.id.clearnewUserForm);
				//clearnewUserForm.setOnClickListener(this);

			} else if (v == newuser) {
				setContentView(R.layout.newuser);
				setTitle(R.string.newuser);
				homepage = (Button) findViewById(R.id.backTohomepagefromnewUsr);
				homepage.setOnClickListener(this);
				EditText username = (EditText) findViewById(R.id.newuser_username);
				EditText password = (EditText) findViewById(R.id.newuser_userpass);
				EditText confirmpassword = (EditText) findViewById(R.id.newuser_userpass1);

				savenewuser = (Button) findViewById(R.id.savenewUser);
				savenewuser.setOnClickListener(this);

				//clearnewUserForm = (Button) findViewById(R.id.clearnewUserForm);
				//clearnewUserForm.setOnClickListener(this);

			} else if (v == savenewuser) {
				EditText username = (EditText) findViewById(R.id.newuser_username);
				EditText password = (EditText) findViewById(R.id.newuser_userpass);
				EditText confirmpassword = (EditText) findViewById(R.id.newuser_userpass1);
				EditText address=(EditText)findViewById(R.id.newuser_address);
				EditText phonenumber=(EditText)findViewById(R.id.newuser_phonenumber);
				EditText firstname=(EditText)findViewById(R.id.newuser_firstname);
				EditText lastname=(EditText)findViewById(R.id.newuser_lastname);
				EditText email = (EditText) findViewById(R.id.newuser_email);
				if (username.getText().length() >= 1
						|| password.getText().length() >= 1) {
					if (this.checkEmail(email.getText().toString())
							|| email.getText().length() > 0) {

						if (password.getText().toString()
								.equals(confirmpassword.getText().toString())) {
							password.setBackgroundColor(0x5500ff00);
							confirmpassword.setBackgroundColor(0x5500ff00);
							email.setBackgroundColor(0x5500ff00);
							RadioGroup rg = (RadioGroup) findViewById(R.id.useTypeRadioGroup);
							RadioButton retailerRB = (RadioButton) findViewById(R.id.retailerRadioButton);
							RadioButton vendorRB = (RadioButton) findViewById(R.id.vendorRadioButton);
							RadioButton userRB = (RadioButton) findViewById(R.id.userRadioButton);
							RadioButton distributorRB = (RadioButton) findViewById(R.id.distributorRadioButton);
							HttpClient client = new DefaultHttpClient();
							try {
								HttpPost request = new HttpPost(urlRequest);
								username = (EditText) findViewById(R.id.newuser_username);
								password = (EditText) findViewById(R.id.newuser_userpass);
								List<NameValuePair> pairs = new ArrayList<NameValuePair>();
								pairs.add(new BasicNameValuePair("username",
										username.getText().toString()));
								pairs.add(new BasicNameValuePair("userpass",
										password.getText().toString()));
								pairs.add(new BasicNameValuePair("useremail",
										email.getText().toString()));
								pairs.add(new BasicNameValuePair("phonenumber", phonenumber.getText().toString()));
								pairs.add(new BasicNameValuePair("address", address.getText().toString()));
								pairs.add(new BasicNameValuePair("firstname", firstname.getText().toString()));
								pairs.add(new BasicNameValuePair("lastname", lastname.getText().toString()));
								if (retailerRB.isSelected()
										|| retailerRB.isChecked()) {
									// this.createMessage("Retailer");
									pairs.add(new BasicNameValuePair(
											"usertype", "Retailer"));
								} else if (distributorRB.isSelected()
										|| distributorRB.isChecked()) {
									// this.createMessage("Distributor");
									pairs.add(new BasicNameValuePair(
											"usertype", "Distributor"));
								} else if (userRB.isSelected()
										|| userRB.isChecked()) {
									// this.createMessage("User");
									pairs.add(new BasicNameValuePair(
											"usertype", "User"));
								} else if (vendorRB.isSelected()
										|| vendorRB.isChecked()) {
									// this.createMessage("Vendor");
									pairs.add(new BasicNameValuePair(
											"usertype", "Vendor"));
								}
								
								request.setEntity(new UrlEncodedFormEntity(
										pairs));
								HttpResponse response = client.execute(request);
								HttpEntity entity = response.getEntity();
								String res = EntityUtils.toString(entity);
								this.createMessage("RES:"+res);
								Log.v("::::::::", res);
								if (res.contains("new")) {
									Log.v("HAHA", "NEW USER");
									
									this.createMessage("Account successfuly created.");
									setContentView(R.layout.main);
									setTitle(R.string.loginpg);
									loginButton = (Button) findViewById(R.id.loginButton);
									usernameTextField = (EditText) findViewById(R.id.usernameTextField);
									passwordTextField = (EditText) findViewById(R.id.passwordTextField);
									usernameLabel = (TextView) findViewById(R.id.usernameLabel);
									passwordLabel = (TextView) findViewById(R.id.passwordLabel);
									loginButton.setOnClickListener(this);
									newuser = (Button) findViewById(R.id.newUser);
									newuser.setOnClickListener(this);
								} else {
									Log.v("HAHA", "OLD OLD OLD USER");
									this.createMessage("The user name already exists. Please choose another usernaem");
									username.setText("");
								}
							} catch (ClientProtocolException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								Log.d("RESPONSE:", "))");
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						} else {
							AlertDialog.Builder builder = new AlertDialog.Builder(
									TravITActivity.this);
							builder.setMessage("Wrong Password");
							builder.setCancelable(false);
							builder.setNeutralButton("Okay",
									new OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.cancel();
										}
									});
							builder.show();
							password.setBackgroundColor(0x88ff0000);
							confirmpassword.setBackgroundColor(0x88ff0000);
						}
					} else {
						this.createMessage("Please Enter a valid email");
						email.setBackgroundColor(0x88ff0000);
					}
				} else {
					this.createMessage("Username or Password cannot be blank. Please enter it again");
				}

			} else if (v == searchProductImageButton) {
				setContentView(R.layout.search_products);
				setTitle(R.string.searprod);
//				TextView tempwelcome = (TextView) findViewById(R.id.homepageUsername);
//				tempwelcome.setText("Welcome " + usernameLabel + "!");
				productCategory = (Spinner) findViewById(R.id.productcategory);
				productName = (Spinner) findViewById(R.id.productname);
				HttpClient client = new DefaultHttpClient();

				HttpGet request = new HttpGet(urlRequestSearchProducts
						+ "?typeOfRequest=TypesOfProducts");

				HttpGet requestlocations = new HttpGet(urlRequestSearchProducts
						+ "?typeOfRequest=ParticularTypeOfProduct");
				try {
					
					tempCategory = (String) productCategory.getSelectedItem();
					HttpResponse response = client.execute(request);
					HttpEntity entity = response.getEntity();
					String responseResult= EntityUtils.toString(entity);
		
					String differentTypesOfProducts[] = responseResult
							.split(";");
					for(int i=0;i<differentTypesOfProducts.length;i++)
					{
						Log.v(""+i, ""+differentTypesOfProducts[i]);
					}
					ArrayAdapter categoryadapter = new ArrayAdapter(TravITActivity.this,
							android.R.layout.simple_spinner_item, differentTypesOfProducts);
					productCategory.setAdapter(categoryadapter);
					
					productCategory.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							// TODO Auto-generated method stub
							Log.v("selected", "is" + productCategory.getSelectedItem().toString());
							tempCategory = (String) productCategory.getSelectedItem().toString();
							Log.v("from category", "" + tempCategory);
							try
							{
								HttpClient client = new DefaultHttpClient();
								HttpGet requestnames = new HttpGet(urlRequestSearchProducts
										+ "?typeOfRequest=ParticularType&nameOfProduct=" + tempCategory);

								HttpResponse responsenames = client.execute(requestnames);
								HttpEntity entitynames = responsenames.getEntity();
								String responseResultnames = EntityUtils.toString(entitynames);
								String differentTypesOfProductsNames[] = responseResultnames
										.split(";");
								for(int i=0;i<differentTypesOfProductsNames.length;i++)
								{
									Log.v(""+i, ""+differentTypesOfProductsNames[i]);
								}
								ArrayAdapter nameadapter = new ArrayAdapter(TravITActivity.this,
										android.R.layout.simple_spinner_item, differentTypesOfProductsNames);
								productName.setAdapter(nameadapter);
			
							} catch (ClientProtocolException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub
							
						}
						
					});

					
					
					
/*					searchProductsListView.setAdapter(new ArrayAdapter<String>(
							TravITActivity.this,
							android.R.layout.simple_list_item_1,
							differentTypesOfProducts));
					searchProductsListView
							.setOnItemClickListener(new OnItemClickListener() {
								@Override
								public void onItemClick(AdapterView<?> a,
										View v, int position, long id) {
									try {
										TravITActivity.this.count = TravITActivity.this.count + 1;
										if (TravITActivity.this.count == 1) {
											HttpClient client = new DefaultHttpClient();
											HttpGet request = new HttpGet(
													urlRequestSearchProducts
															+ "?typeOfRequest=ParticularType&nameOfProduct="
															+ Uri.encode(searchProductsListView
																	.getItemAtPosition(
																			position)
																	.toString()));
											HttpResponse response = client
													.execute(request);
											HttpEntity entity = response
													.getEntity();
											String responseResult = EntityUtils
													.toString(entity);
											String particularTypesOfProducts[] = responseResult
													.split(";");
											searchProductsListView
													.setAdapter(new ArrayAdapter<String>(
															TravITActivity.this,
															android.R.layout.simple_list_item_1,
															particularTypesOfProducts));
										} else if (TravITActivity.this.count == 2) {
											HttpClient client = new DefaultHttpClient();
											Log.v("diff:",
													searchProductsListView
															.getItemAtPosition(
																	position)
															.toString());
											HttpGet request = new HttpGet(
													urlRequestSearchProducts
															+ "?typeOfRequest=ParticularTypeOfProduct&productName="
															+ Uri.encode(searchProductsListView
																	.getItemAtPosition(
																			position)
																	.toString()));
											HttpResponse response = client
													.execute(request);
											HttpEntity entity = response
													.getEntity();
											String responseResult = EntityUtils
													.toString(entity);
											String particularProduct[] = responseResult
													.split(";");
											searchProductsListView
													.setAdapter(new ArrayAdapter<String>(
															TravITActivity.this,
															android.R.layout.simple_list_item_1,
															particularProduct));
										}

									} catch (ClientProtocolException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}
							});
*/
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
				homepageImageButton = (ImageButton) findViewById(R.id.homepage);
				homepageImageButton.setOnClickListener(this);
				logoutImageButton = (ImageButton) findViewById(R.id.logout);
				logoutImageButton.setOnClickListener(this);
				searchParticularProduct = (Button) findViewById(R.id.searchproductsbutton);
				searchParticularProduct.setOnClickListener(this);
				
			} else if (v == searchParticularProduct) {
				tempName = (String) productName.getSelectedItem();
				//tempName = tempName.trim();
				setContentView(R.layout.search_particular_products_);
				setTitle(R.string.searprod);
				HttpClient client = new DefaultHttpClient();
				Log.v("temp is", tempName);
				HttpGet request = new HttpGet(urlRequestSearchProducts
						+ "?typeOfRequest=ParticularTypeOfProduct&productsName=" + Uri.encode(tempName));

				try
				{
					Log.v("in", "try");
					Log.v("request", ""+request.getAllHeaders().toString());
					HttpResponse response = client.execute(request);
					Log.v("response", ""+response);
					HttpEntity entity = response.getEntity();
					Log.v("entity", ""+entity.toString());
					//Log.v("check response", EntityUtils.toString(entity));
					String responseResult = EntityUtils.toString(entity);
					Log.v("search result response", responseResult);
					Log.v("check", "check");
					String listOfStoresbyproducts[] = responseResult.split(";");
					for(int i=0;i<listOfStoresbyproducts.length;i++)
					{
						Log.v(""+i, ""+listOfStoresbyproducts[i]);
						
					}
					ListView searchStoreByCityResultsView = (ListView) findViewById(R.id.searchParticularProduct);
					searchStoreByCityResultsView
							.setAdapter(new ArrayAdapter<String>(TravITActivity.this,
									android.R.layout.simple_list_item_1, listOfStoresbyproducts));
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				homepageImageButton = (ImageButton) findViewById(R.id.homepage);
				homepageImageButton.setOnClickListener(this);
				logoutImageButton = (ImageButton) findViewById(R.id.logout);
				logoutImageButton.setOnClickListener(this);
			}
			
			else if (v == clearnewUserForm) {

				EditText username = (EditText) findViewById(R.id.newuser_username);
				EditText password = (EditText) findViewById(R.id.newuser_userpass);
				EditText confirmpassword = (EditText) findViewById(R.id.newuser_userpass1);
				EditText email = (EditText) findViewById(R.id.newuser_email);
				username.setText("");
				password.setText("");
				confirmpassword.setText("");
				email.setText("");
			} else if (v == deleteProfileUserButton) {
				TextView username = (TextView) findViewById(R.id.showProfileusername);
				HttpClient client = new DefaultHttpClient();
				HttpDelete request = new HttpDelete(urlRequest + "?username="
						+ username.getText().toString());
				try {
					HttpResponse response = client.execute(request);
					HttpEntity entity = response.getEntity();
					String responseResult = EntityUtils.toString(entity);
					if (responseResult.equals("Deleted")) {
						this.createMessage("Account Deleted");
						setContentView(R.layout.main);
						setTitle(R.string.loginpg);
						loginButton = (Button) findViewById(R.id.loginButton);
						usernameTextField = (EditText) findViewById(R.id.usernameTextField);
						passwordTextField = (EditText) findViewById(R.id.passwordTextField);
						usernameLabel = (TextView) findViewById(R.id.usernameLabel);
						passwordLabel = (TextView) findViewById(R.id.passwordLabel);
						loginButton.setOnClickListener(this);
						newuser = (Button) findViewById(R.id.newUser);
						newuser.setOnClickListener(this);

					}

				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else if (v == homepage) {
				Log.i("login", "user");
				setContentView(R.layout.main);
				setTitle(R.string.loginpg);
				loginButton = (Button) findViewById(R.id.loginButton);
				usernameTextField = (EditText) findViewById(R.id.usernameTextField);
				passwordTextField = (EditText) findViewById(R.id.passwordTextField);
				usernameLabel = (TextView) findViewById(R.id.usernameLabel);
				passwordLabel = (TextView) findViewById(R.id.passwordLabel);
				loginButton.setOnClickListener(this);
				newuser = (Button) findViewById(R.id.newUser);
				newuser.setOnClickListener(this);

			} else if (v == homepageImageButton) {
				Log.i("login", "user");
				setContentView(R.layout.homepage);
				setTitle(R.string.userhome);
				searchProductImageButton = (ImageButton) findViewById(R.id.searchProductIcon);
				scanBarCodeImageButton = (ImageButton) findViewById(R.id.scanBarcodeIcon);
				userManageProfileImageButton = (ImageButton) findViewById(R.id.userManageProfile);
				// homepageImageButton=(ImageButton)findViewById(R.id.homepageButton);
				// gobackImageButton=(ImageButton)findViewById(R.id.goBackButton);
				searchStoreIconImageButton = (ImageButton) findViewById(R.id.searchStoreIcon);
				logoutImageButton = (ImageButton) findViewById(R.id.logout);
				TextView name = (TextView) findViewById(R.id.homepageUsername);
				Editable username = usernameTextField.getText();
				name.setText("Welcome " + username + "!");
				// searchImageButton.setImageResource(R.drawable.search);
				// scanBarCodeImageButton.setImageResource(R.drawable.scanbarcode);
				// userManageProfileImageButton.setImageResource(R.drawable.userprofilemanagement);
				// homepageImageButton.setImageResource(R.drawable.homepage);
				// gobackImageButton.setImageResource(R.drawable.go_back);
				// searchStoreIconImageButton.setImageResource(R.drawable.search_store);
				// logoutImageButton.setImageResource(R.drawable.logout);
				logoutImageButton.setOnClickListener(this);
				// homepageImageButton.setOnClickListener(this);
				// gobackImageButton.setOnClickListener(this);
				userManageProfileImageButton.setOnClickListener(this);
				searchStoreIconImageButton = (ImageButton) findViewById(R.id.searchStoreIcon);
				searchStoreIconImageButton.setOnClickListener(this);
				searchProductImageButton.setOnClickListener(this);
				TravITActivity.this.count = 0;
			} else if (v == updateProfileUserButton) {
				TextView username = (TextView) findViewById(R.id.showProfileusername);
				HttpClient client = new DefaultHttpClient();
				TextView email = (TextView) findViewById(R.id.showProfileEmail);
				Log.v("email displayed:", email.getText().toString());
				if (this.checkEmail(email.getText().toString())) {
					HttpPut request = new HttpPut(urlRequest + "?username="
							+ username.getText().toString() + "&useremail="
							+ email.getText().toString());
					try {
						// request.setEntity(new UrlEncodedFormEntity(pairs));
						HttpResponse response = client.execute(request);
						HttpEntity entity = response.getEntity();
						String res = EntityUtils.toString(entity);
						Log.v("res", res);
						this.createMessage("Updated profile");
						this.onClick(homepageImageButton);

					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					this.createMessage("Not a valid email. Please enter it again");
				}

			} else if (v == userManageProfileImageButton) {
//				Intent newIntent = new Intent(v.getContext(), UserProfileManage.class);
//				newIntent.putExtra("venid", loggedid);
//				String user = usernameTextField.getText().toString();
//				String pass = passwordTextField.getText().toString();
//				Log.v("putting user", user);
//				Log.v("putting user", pass);
//				newIntent.putExtra("inusername", user);
//				newIntent.putExtra("inuserpass", pass);
//				startActivity(newIntent);
				setContentView(R.layout.profile);
				setTitle(R.string.prof);
				EditText profileEmail = (EditText) findViewById(R.id.showProfileEmail);
				TextView profileUsername = (TextView) findViewById(R.id.showProfileusername);
				Log.v("username:", usernameTextField.getText().toString());
				HttpClient client = new DefaultHttpClient();
				HttpGet request = new HttpGet(urlRequest + "?username="
						+ usernameTextField.getText().toString() + "&userpass="
						+ passwordTextField.getText().toString());
				Log.v("see", "see");
				try {
					HttpResponse response = client.execute(request);
					HttpEntity entity = response.getEntity();
					String responseResult = EntityUtils.toString(entity);
					Log.v("PROFILE:", responseResult);
					String[] table = responseResult.split(",");
					Hashtable<String, String> tableHashtable = new Hashtable();
					for (int i = 0; i < table.length; i++) {
						//Log.v(table[i], table[++i]);
						tableHashtable.put(table[i], table[++i]);
					}
					System.out.println("check:");
					profileUsername.setText(tableHashtable.get("username"));
					// profileUsername.setEnabled(false);
					profileEmail.setText(tableHashtable.get("email"));
					// profileUsername.setClickable(false);
					TextView userType = (TextView) findViewById(R.id.userIDProfile);
					userType.setText(tableHashtable.get("usertype"));
					TextView address = (TextView) findViewById(R.id.showProfileAddress);
					address.setText(tableHashtable.get("address"));
					TextView city = (TextView) findViewById(R.id.showProfileCity);
					city.setText(tableHashtable.get("city"));
					TextView state = (TextView) findViewById(R.id.showProfileState);
					state.setText(tableHashtable.get("state"));
					TextView phone = (TextView) findViewById(R.id.showProfilePhone);
					phone.setText(tableHashtable.get("phonenumber"));
					TextView zip=(TextView)findViewById(R.id.showProfileZipcode);
					zip.setText(tableHashtable.get("zipcode"));
					homepageImageButton = (ImageButton) findViewById(R.id.homepage);
					//gobackImageButton = (ImageButton) findViewById(R.id.goBackButton);
					// homepageImageButton.setImageResource(R.drawable.homepage);
					// gobackImageButton.setImageResource(R.drawable.go_back);
					homepageImageButton.setOnClickListener(this);
					//gobackImageButton.setOnClickListener(this);
					deleteProfileUserButton = (Button) findViewById(R.id.deleteProfileUser);
					updateProfileUserButton = (Button) findViewById(R.id.updateProfileUser);
					deleteProfileUserButton.setOnClickListener(this);
					updateProfileUserButton.setOnClickListener(this);
					logoutImageButton = (ImageButton) findViewById(R.id.logout);
					logoutImageButton.setOnClickListener(this);

				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}

		public void createMessage(String msg) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TravITActivity.this);
			builder.setMessage(msg);
			builder.setCancelable(false);
			builder.setNeutralButton("Okay", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			});
			builder.show();
		}

		public void createMessageWithYesOrNo(String msg) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TravITActivity.this);
			builder.setMessage(msg);
			builder.setCancelable(false);
			builder.setPositiveButton("Yes", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			});
			builder.setNegativeButton("No", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
				}
			});
			builder.show();
		}

		public boolean checkEmail(String Email) {
			if (Email.length() == 0) {
				return false;
			}
			String pttn = "^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+.([a-zA-Z])+([a-zA-Z])+";
			Pattern p = Pattern.compile(pttn);
			Matcher m = p.matcher(Email);
			if (m.matches()) {
				return true;
			}
			return false;
		}
/*		public void onActivityResult(int requestCode, int resultCode, Intent intent) {
			this.createMessage(""+requestCode);
	    	this.createMessage(""+resultCode);
	    	this.createMessage(""+intent.toString());
	    
		    if (requestCode == 0) {
		        if (resultCode == RESULT_OK) {
		            String contents = intent.getStringExtra("SCAN_RESULT");
		            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
		            this.createMessage(contents);
		            this.createMessage(format);
		            // Handle successful scan
		            Log.v("scanned id", contents);
		            
		        } else if (resultCode == RESULT_CANCELED) {
		            // Handle cancel
		        }
		    }
		}
*/
	}
	 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		 clicker c=new clicker();
			//c.createMessage("requestCode:"+requestCode);
	    //	c.createMessage("resultcode:"+resultCode);
	    //	c.createMessage("intent:"+intent.toString());
	    	
	    
		    if (requestCode == 0) {
		        if (resultCode == RESULT_OK) {
		            String contents = intent.getStringExtra("SCAN_RESULT");
		            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
		        	HttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(urlBarCodeRequest + "?boxbarcodeID="+contents);
					Log.v("rty","try");
					try {
						HttpResponse response = client.execute(request);
						HttpEntity entity = response.getEntity();
						String responseResult = EntityUtils.toString(entity);
						if(responseResult.trim().equals("false")){
							c.createMessage("Invalid Product.");
						}else{
							
						//Log.v("response",EntityUtils.toString(entity));
						//Log.v("reponseResile",responseResult[0]+":"+responseResult[1]);
						//Log.v("reponseResile",responseResult[2]+":"+responseResult[3]);
							String responseTable[]=responseResult.split(";");
							String comingFromAddress="";
							for(int i=0;i<responseTable.length;i++){
							comingFromAddress=comingFromAddress+responseTable[i]+"->";
							}
							comingFromAddress+="To you";
							c.createMessage("This product is coming from:"+comingFromAddress);
						}
					}catch(Exception e){	
					}
		            //c.createMessage("Decoded String:"+contents);
		            //c.createMessage("formatL"+format);
		            // Handle successful scan
					
					if(savehistory == true)
					{
						HttpGet requestproduct = new HttpGet(urlRequestForHistory
			    				+ "?barcodeID="+contents);
			    		HttpClient client1 = new DefaultHttpClient();
			    		Hashtable<String,String> table;
			    		String[] responseResultArr = null;
			    		try{
			    			HttpResponse response1=client.execute(request);
			    			HttpEntity entity1 = response1.getEntity();
			    			Log.v("entity:",entity1.toString());
			    			String responseResult = EntityUtils.toString(entity1);
			    			Log.v("Box Results::",responseResult);
			    			
			    			Log.v("hahahahhahaha","hahahahhaha");
			    			responseResultArr=responseResult.split(";");
			    			table=new Hashtable<String,String>();
			    			for(int i=0;i<responseResultArr.length;i+=2)
			    			{
			    				Log.v("response:",responseResultArr[i]);
			    				int tempVar=i;
			    				tempVar++;
			    				Log.v("result:",responseResultArr[tempVar]);
			    				table.put(responseResultArr[i],responseResultArr[tempVar]);
			    			}
			    		} catch(Exception e) {
			    			// TODO Auto-generated catch block
			    			e.printStackTrace();
			    		}
			    		
			    		//1 and 3
						HttpClient client2 = new DefaultHttpClient();
						try {
							HttpPost request2 = new HttpPost(urlRequestForHistory + "");
							List<NameValuePair> pairs = new ArrayList<NameValuePair>();
							pairs = new ArrayList<NameValuePair>();
							pairs.add(new BasicNameValuePair("scanningID",
									loggedid));
							pairs.add(new BasicNameValuePair("scanningName",
									loggedinuser));
							pairs.add(new BasicNameValuePair("scanningType",
									"UserValidation"));
							pairs.add(new BasicNameValuePair("scannedID",
									contents));
							pairs.add(new BasicNameValuePair("name",
									responseResultArr[1]));
							pairs.add(new BasicNameValuePair("category",
									responseResultArr[3]));
							request2.setEntity(new UrlEncodedFormEntity(
									pairs));
							HttpResponse response2 = client2.execute(request2);
							HttpEntity entity2 = response2.getEntity();
							String res2 = EntityUtils.toString(entity2).trim();
						}catch(Exception e){
							
						}
					}
		        } else if (resultCode == RESULT_CANCELED) {
		            // Handle cancel
		        }
		    }
		}

}
